package com.wh.message.mail.service.impl;

import com.wh.common.util.Result;
import com.wh.message.mail.in.MailIn;
import com.wh.message.mail.service.MailService;
import com.wh.message.utils.ValidatorFactoryUtil;
import com.wh.msg.ResultCode;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;



/**
 * 邮件服务
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mq.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service
public class MailServiceImpl implements MailService {

    Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    /**
     * 发送邮件标题
     */
    @Value("#{settings['mail.personal']}")
    private String personal;

    /**
     * 邮件发送对象
     */
    private JavaMailSenderImpl javaMailSenderImpl;

    public void setJavaMailSenderImpl(JavaMailSenderImpl javaMailSenderImpl) {
        this.javaMailSenderImpl = javaMailSenderImpl;
    }


    /**
     * 发送邮件
     * @param mailIn 邮件入参
     * @return
     */
    @Override
    public Result sendMail(MailIn mailIn){
        logger.info("sendMail邮件发送-->>开始");
        logger.info("sendMail邮件发送mailIn = {}", JSONObject.fromObject(mailIn).toString());
        Result result = new Result();
        try {
            result= ValidatorFactoryUtil.validate(mailIn);
            if(!ResultCode.RES_OK.equals(result.getResCode())){
                logger.info("sendMail邮件发送，参数校验不通过,result = {}",result);
                return result;
            }
            //将发送邮箱List变为数组
            String[] mailArray = (mailIn.getEmailString().split(","));
            MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            messageHelper.setFrom(javaMailSenderImpl.getUsername(), personal);
            //邮件主题
            messageHelper.setSubject(mailIn.getTitle());
            //发送地址
            messageHelper.setTo(mailArray);
            //发送内容
            messageHelper.setText(mailIn.getContent(), mailIn.isHtml());
            //调用发送服务
            javaMailSenderImpl.send(mimeMessage);
        }catch (Exception e){
            logger.error("sendMail邮件发送出现异常msg = {}",e.getMessage());
            e.printStackTrace();
            result.setResCode(ResultCode.RES_ERR);
            result.setResult(e.getMessage());
        }
        logger.info("sendMail邮件发送-->>结束");
        return result;
    }



}
